<template>
  <div class="container">
    <!-- 左侧功能栏 -->
    <div class="sidebar">
      <el-menu
          router
          :default-active="$route.path"
          class="el-menu-vertical-demo"
          background-color="#f4f4f4"
          text-color="#333"
          active-text-color="#409EFF"
      >
        <el-menu-item index="/chat">
          <i class="el-icon-menu"></i>对话
        </el-menu-item>
        <el-menu-item index="/api/goods">
          <i class="el-icon-document"></i>购买
        </el-menu-item>
        <el-menu-item index="/home">
          <i class="el-icon-setting"></i>个人中心
        </el-menu-item>
      </el-menu>

      <!-- 底部按钮部分 -->
      <div class="sidebar-bottom">
        <el-button type="primary" size="small" @click="editProfile">个人信息修改</el-button>
        <el-button type="danger" size="small" @click="confirmLogout">退出登录</el-button>
      </div>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <h2>充值tokens</h2>

      <!-- 固定套餐选项 -->
      <div class="package-cards">
        <div class="package-card" v-for="pkg in packages" :key="pkg.value">
          <label>
            <input
                type="radio"
                v-model="selectedPackage"
                :value="pkg.value"
            />
            <div class="card-content">
              <p>{{ pkg.tokens }} Tokens</p>
              <p>{{ pkg.price }}元</p>
            </div>
          </label>
        </div>
      </div>

      <!-- 支付方式（仅支付宝） -->
      <div class="payment-method">
        <p>支付方式：支付宝</p>
      </div>

      <!-- 充值按钮 -->
      <button class="content-button" @click="rechargeTokens">充值</button>

      <!-- 消息提示 -->
      <p v-if="message" class="message">{{ message }}</p>
      <p v-if="orderId" class="order-id">订单编号: {{ orderId }}</p>
    </div>
  </div>
</template>

<script>
const baseUrl = "http://localhost:8090";
export default {
  name: 'GoodsTable',
  data() {
    return {
      selectedPackage: null,
      message: "",
      orderId: "",
      packages: [
        { value: 10, tokens: 1000, price: 10 },
        { value: 50, tokens: 5000, price: 50 },
        { value: 100, tokens: 10000, price: 100 },
      ],
    };
  },
  created() {
    this.load();
  },

  methods: {
    generateOrderId() {
      const timestamp = Date.now(); // 当前时间戳
      const randomNum = Math.floor(Math.random() * 1000000); // 随机生成的六位数
      return `ORDER-${timestamp}-${randomNum}`;
    },
    rechargeTokens() {
      // 确保选择了一个有效的套餐
      if (!this.selectedPackage) {
        this.message = "请选择一个代币套餐.";
        return;
      }
      // 生成订单号
      this.orderId = this.generateOrderId();
      // 处理充值逻辑
      const paymentUrl = `${baseUrl}/alipay/pay?subject=${localStorage.getItem("username")}&traceNo=${this.orderId}&totalAmount=${this.selectedPackage}`;
      window.open(paymentUrl);
      this.$message.success("请求支付宝成功");
    },
    editProfile() {
      this.$message('个人信息修改功能尚未实现！');
    },
    confirmLogout() {
      this.$confirm('确定要退出吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        });
      });
    },
    logout() {
      localStorage.removeItem('user');
      this.$message.success('已退出登录');
      this.$router.push('/login');
    },
    load() {
      fetch(baseUrl + '/api/goods', {
        mode: 'cors'
      })
          .then(res => res.json())
          .then(res => {
            this.tableData = res;
          })
          .catch(err => {
            console.error('Fetch error:', err);
          });
    },

  }
}
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh; /* 页面高度 */
}

.sidebar {
  width: 240px;
  background-color: #f4f4f4;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 使左侧栏内容和底部按钮上下分布 */
}

.sidebar-bottom {
  display: flex;
  justify-content: space-between; /* 按钮水平排列，左右分布 */
  align-items: center;
}

.sidebar-bottom .el-button {
  flex: 1;
  margin-right: 10px; /* 按钮之间的间距 */
}

.sidebar-bottom .el-button:last-child {
  margin-right: 0; /* 取消最后一个按钮的右侧间距 */
}

.content {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 500px;
  text-align: center;
  margin: 50px auto;
}

h2 {
  margin-bottom: 20px;
  color: #333
}

.package-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.package-card {
  background-color: #f4f4f4;
  padding: 15px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.package-card:hover {
  background-color: #ecf0f1;
}

.card-content {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
}

input[type="radio"] {
  margin-right: 10px;
}

.content-button {
  width: 100%;
  padding: 12px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #16a085;
}

.payment-method {
  margin: 20px 0;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.message {
  margin-top: 20px;
  font-weight: bold;
  color: green;
}
.order-id {
  margin-top: 10px;
  color: #888;
}
</style>
